<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { CustomMouseMenu } from '@/plugins/directive/contextmenu';
import { ElMessageBox, ElMessage } from 'element-plus';
import { TabType } from '@/types/global/tab';
import useStore from '@/store';
import { ButtonType } from '@/types/components/container';
import { AppTypeEnum } from '@/enums';
defineOptions({ name: 'App' });

const treeRef = ref(null);
const tableRef = ref(null);
const loading = ref(true);
const treeLoading = ref(true);

const currentRow = ref(null);
const currentAppCatalogRow = ref(null);
const appCatlogs = ref(null);
const apps = ref(null);
const buttons = reactive([
  {
    icon: 'CirclePlus',
    fn: () => {
      add();
    },
  },
  {
    icon: 'Edit',
    fn: () => {
      if (!currentRow.value) {
        ElMessage.error('请先选中要修改的行!');
        return;
      }
      edit(currentRow.value.id, currentRow.value.name);
    },
  },
  { icon: 'Delete' },
] as Array<ButtonType>);
const handleTreeNodeClick = row => {
  currentAppCatalogRow.value = row;
  nextTick(() => {
    getApps(currentAppCatalogRow.value.id);
    treeRef.value.setCurrentKey(currentAppCatalogRow.value.id);
  });
};
const handleTableRowClick = row => {
  currentRow.value = row;
  nextTick(() => {
    tableRef.value.setCurrentRow(currentRow.value);
  });
};
const remove = (ids: Number | Array<Number>, name?: String) => {
  let confirmMessage = '是否删除选中的应用?';
  if (ids.constructor === Number) {
    confirmMessage = '是否删除应用（' + name + '）?';
    ids = [ids];
  }

  ElMessageBox.confirm(confirmMessage, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      window.$api.module.remove(ids).then(res => {
        ElMessage.success('删除成功');
        query();
      });
    })
    .catch(() => {});
};
const query = (): void => {
  window.$api.app.getCatalogs().then(res => {
    appCatlogs.value = res.data;
    if (!currentRow.value) {
      handleTreeNodeClick(appCatlogs.value[0]);
    }
    treeLoading.value = false;
  });
};
const getApps = (pId: number) => {
  loading.value = true;
  window.$api.app.getByPId(pId).then(res => {
    apps.value = res.data;
    loading.value = false;
  });
};
const appFormInit = (row?) => {
  let component = 'AppForm';
  let name = component;
  let lable = '应用添加';
  let params = null;
  if (row) {
    name = name + row.id;
    lable = '应用修改';
    params = { id: row.id };
  }
  const tab: TabType = { name: name, component: component, label: lable, icon: 'edit', width: 600, height: 500, params };
  useStore.tab.tabAdd(tab);
};
const add = () => {
  const tab: TabType = { name: 'AppForm', component: 'AppForm', label: '应用添加', icon: 'edit', width: 600, height: 500 };
  useStore.tab.tabAdd(tab);
};
const edit = (id: Number, name: String) => {
  const tab: TabType = { name: 'AppForm' + id, component: 'AppForm', label: '应用修改（' + name + '）', icon: 'edit', width: 600, height: 500, params: { id } };
  useStore.tab.tabAdd(tab);
};
const getContextmenus = (type: number, id: Number, name: String) => {
  let menus = [
    {
      label: '修改',
      icon: 'Edit',
      fn: () => {
        edit(id, name);
      },
    },

    {
      label: '删除',
      icon: 'Delete',
      fn: () => {
        remove(id, name);
      },
    },
  ];
  if (type == AppTypeEnum.App) {
    menus.push({
      label: '资源添加',
      icon: 'Edit',
      fn: () => {
        resourceAdd(id, name);
      },
    });
  }
  return { menus };
};
const resourceAdd = (appId, appName) => {
  const tab: TabType = { name: 'ResourceForm', component: 'ResourceForm', label: '(' + appName + ')资源添加', icon: 'edit', width: 400, height: 350, params: { appId } };
  useStore.tab.tabAdd(tab);
};
const resourceEdit = (id: number, name: string, appName: string) => {
  const tab: TabType = {
    name: 'ResourceForm' + id,
    component: 'ResourceForm',
    label: '(' + appName + ')资源修改（' + name + '）',
    icon: 'edit',
    width: 400,
    height: 350,
    params: { id },
  };
  useStore.tab.tabAdd(tab);
};
const getOperateContextmenus = (id: number, name: string, appName: string) => {
  return {
    menus: [
      {
        label: '修改',
        icon: 'Edit',
        fn: () => {
          resourceEdit(id, name, appName);
        },
      },
      {
        label: '删除',
        icon: 'Delete',
        fn: () => {
          remove(id, name);
        },
      },
    ],
  };
};
const showMouseMenu = (row, column, event) => {
  const ctx = CustomMouseMenu({
    el: event.currentTarget,
    mouse: event,
    ...getContextmenus(row.type, row.id, row.name),
  });
  ctx.show();
  currentRow.value = row;
  tableRef.value.setCurrentRow(row);
};
const showAppCatalogMouseMenu = (event, data) => {
  const ctx = CustomMouseMenu({
    el: event.currentTarget,
    mouse: event,
    ...getContextmenus(data.type, data.id, data.name),
  });
  ctx.show();
  currentAppCatalogRow.value = data;
  treeRef.value.setCurrentKey(data.id);
  getApps(data.id);
};
const showOperateMouseMenu = (row, column, event) => {
  const ctx = CustomMouseMenu({
    el: event.currentTarget,
    mouse: event,
    ...getOperateContextmenus(row.id, row.name, row.appName),
  });
  ctx.show();
  //currentRow.value = row;
  nextTick(() => {
    //tableRef.value.setCurrentRow(row);
  });
};

onMounted(() => {
  query();
});
</script>

<template>
  <windows-form :buttons="buttons" class="app">
    <template #mainleft>
      <el-tree
        ref="treeRef"
        @node-click="handleTreeNodeClick"
        @node-contextmenu="showAppCatalogMouseMenu"
        node-key="id"
        :data="appCatlogs"
        :props="{
          children: 'children',
          label: 'name',
        }"
        default-expand-all
        highlight-current
        :expand-on-click-node="false"
        v-loading="treeLoading"
      >
        <template #default="scope">
          <div class="custom-node">
            <el-image :src="scope.data.icon" style="width: 25px" fit="contain" />
            <span>{{ scope.node.label }}</span>
          </div>
        </template>
      </el-tree>
    </template>
    <el-table ref="tableRef" :data="apps" style="width: 100%" height="100%" highlight-current-row @row-contextmenu="showMouseMenu" @row-click="handleTableRowClick" v-loading="loading">
      <el-table-column type="expand">
        <template #default="props">
          <div style="padding: 10px 20px">
            <el-table :data="props.row.resources" style="width: 100%" height="100%" border @row-contextmenu="showOperateMouseMenu" @contextmenu="handleTableRowClick(props.row)">
              <el-table-column type="index" width="80" label="序号" align="center" />
              <el-table-column label="资源名称" prop="name" width="150" align="center" />
              <el-table-column label="所属应用" prop="appName" width="200" align="center" />
              <el-table-column label="许可证" prop="license" width="200" align="center" />
              <el-table-column label="备注" prop="remark" minWidth="150" align="center" />
              <el-table-column prop="createdOn" label="创建日期" width="150" align="center"></el-table-column>
              <el-table-column prop="createdByName" label="创建人" width="100" align="center"></el-table-column>
              <el-table-column prop="updatedOn" label="更新日期" width="150" align="center"></el-table-column>
              <el-table-column prop="updatedByName" label="更新人" width="100" align="center"></el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column type="index" width="80" label="序号" align="center" />
      <el-table-column prop="name" label="应用名称" align="center" width="150">
        <template #default="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="icon" label="图标" align="center" width="60">
        <template #default="scope">
          <div style="display: flex; justify-content: center">
            <el-image style="width: 25px" :src="scope.row.icon" fit="contain" />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="appCatalogName" label="所属目录" align="center" width="150"></el-table-column>
      <el-table-column prop="component" label="组件" align="center" minWidth="150"></el-table-column>
      <el-table-column label="许可证" prop="license" width="200" align="center" />
      <el-table-column prop="showCorner" label="角落显示" align="center" width="100"></el-table-column>
      <el-table-column prop="width" label="宽度" align="center" width="80"></el-table-column>
      <el-table-column prop="height" label="高度" align="center" width="80"></el-table-column>
      <el-table-column prop="sort" label="排序" align="center" width="80"></el-table-column>
      <el-table-column prop="remark" label="备注" align="center" minWidth="150"></el-table-column>
      <el-table-column prop="createdOn" label="创建日期" align="center" width="150"></el-table-column>
      <el-table-column prop="createdByName" label="创建人" align="center" width="100"></el-table-column>
      <el-table-column prop="updatedOn" label="更新日期" align="center" width="150"></el-table-column>
      <el-table-column prop="updatedByName" label="更新人" align="center" width="100"></el-table-column>
    </el-table>
  </windows-form>
</template>
<style lang="scss">
.app {
  .el-tree {
    .el-tree-node__content {
      height: 30px;
      margin: 3px 0px;
    }
  }
}
</style>
<style scoped lang="scss">
.app .el-table .cell {
  display: flex;
  align-items: center;
}
.cell_name {
  display: flex;
  align-items: center;
  span {
    margin-left: 5px;
  }
}
.btngroup {
  height: 50px;
  display: flex;
  align-items: center;
  .el-icon {
    font-size: 18px;
    color: #909399;
    margin-right: 15px;
  }
}
.el-tree {
  width: 180px;
  .el-tree-node__content {
    height: 30px;
  }
}
.custom-node {
  display: flex;
  align-items: center;
  span {
    margin-left: 5px;
  }
}
</style>
